/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑, 永无BUG!
 * 　　　　┃　　　┃Code is far away from bug with the animal protecting
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 */
package com.zkgengkun.support.generator;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zkgengkun.support.generator.tools.FreemarkerUtils;
import com.zkgengkun.support.generator.tools.Table;
import com.zkgengkun.support.util.buffer.OsPathBuffer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


/**
 * @author gengshikun
 * @date 2017/7/5
 */
public class MybatisGeneratorXml {

//    protected String location="D:\\Work\\lib\\mysql-connector-java-5.1.9.jar";
//    protected String dbUrl="192.168.10.9:3306";
//    protected String dbName="hbdiy-300-upms";
//    protected String userId = "dev";
//    protected String password = "dev123";
//    protected String basePackage="com.hbdiy.ec";


    public static void generatorXML(String location, String dbUrl, String dbName, String userId, String password, String basePackage) {
        String path = Class.class.getClass().getResource("/").getPath();
        String targetProject = findProjectName(path);
        String modelTargetProject = targetProject;
        String connectionUrl = "jdbc:mysql://" + dbUrl + "/" + dbName + "";

        String modelTargetPackage = basePackage + ".model.po";
        String sqlMapTargetPackage = basePackage + ".dao.table.mapper";
        String javaClientTargetPackage = basePackage + ".dao.table.mapper";

        String projectBasePath = findProjectBasePath(path);
        String mapperDirectoryPath = new OsPathBuffer().append(projectBasePath).append("/src/main/java/" + sqlMapTargetPackage.replace(".", "//")).toString();
        String poDirectoryPath = new OsPathBuffer().append(projectBasePath).append("/src/main/java/" + modelTargetPackage.replace(".", "//")).toString();


        removeFile(mapperDirectoryPath, poDirectoryPath);

        List<Table> tableList = Lists.newArrayList();
        List<Map<String, Object>> tableNameList = getAllTableFromDb(dbUrl, dbName, userId, password);

        for (Map<String, Object> map : tableNameList) {
            tableList.add(new Table(map.get("table_name").toString()));
        }

        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("location", location);
        dataMap.put("connectionUrl", connectionUrl);
        dataMap.put("userId", userId);
        dataMap.put("password", password);
        dataMap.put("modelTargetPackage", modelTargetPackage);

        dataMap.put("sqlMapTargetPackage", sqlMapTargetPackage);
        dataMap.put("javaClientTargetPackage", javaClientTargetPackage);
        dataMap.put("targetProject", targetProject);
        dataMap.put("modelTargetProject", modelTargetProject);

        dataMap.put("tablesList", tableList);

        String suffix = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        System.out.println(suffix);
        try {
            FreemarkerUtils.generateToFile("", "generatorConfigTemplate.ftl", "generator/generatorConfig.xml", dataMap, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文件生成完毕");
    }


    private static String findProjectName(String path) {
        path = path.substring(0, path.length() - 16);
        String projectName = path.substring(path.lastIndexOf("/") + 1, path.length());
        return projectName;
    }

    private static String findProjectBasePath(String path) {
        path = path.substring(0, path.length() - 16);
        return path;
    }


    private static List<Map<String, Object>> getAllTableFromDb(String dbUrl, String dbName, String userId, String password) {

        String url = "jdbc:mysql://" + dbUrl + "/" + dbName + "?useUnicode=yes&characterEncoding=UTF8";
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(userId);
        dataSource.setPassword(password);

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '" + dbName + "'";
        List<Map<String, Object>> tableNameList = jdbcTemplate.queryForList(sql);
        return tableNameList;
    }

    private static void removeFile(String mapperDirectoryPath, String poDirectoryPath) {
        File mapperDirectory = new File(mapperDirectoryPath);
        System.out.println(mapperDirectory.getAbsolutePath());
        System.out.println(mapperDirectory.exists());
        if (mapperDirectory.isDirectory()) {
            File[] mapperFiles = mapperDirectory.listFiles();
            for (File file : mapperFiles) {
                file.delete();
            }
        }
        System.out.println("mapperDirectory 清空..............");

        File poDirectory = new File(poDirectoryPath);
        if (poDirectory.isDirectory()) {
            File[] poFiles = poDirectory.listFiles();
            for (File file : poFiles) {
                file.delete();
            }
        }
        System.out.println("poDirectoryPath 清空..............");
    }

}
